#include "aabb.h"

AABB::AABB(Vectorf *aMin, Vectorf *aMax) : min(aMin), max(aMax)
{
    type=1;
    translation= new Vectorf(0,0,0);
}

AABB::AABB(Vectorf *aMin, Vectorf *aMax, Vectorf *aTranslation) : min(aMin), max(aMax)
{
    type=1;
    translation=aTranslation;
}


AABB * AABB::SetAABB()
{
    Vectorf * min= new Vectorf(GetVertex(0));
    Vectorf * max= new Vectorf(GetVertex(0));

    for(int i=1;i<vertexCount;i++)
    {
        Vectorf * temp= new Vectorf(GetVertex(i));

        if(temp->x()<min->x())
        {
            min->x(temp->x());
        }
        if(temp->x()>max->x())
        {
            max->x(temp->x());
        }

        if(temp->y()<min->x())
        {
            min->y(temp->y());
        }
        if(temp->y()>max->y())
        {
            max->y(temp->y());
        }

        if(temp->z()<min->z())
        {
            min->z(temp->z());
        }
        if(temp->z()>max->z())
        {
            max->z(temp->z());
        }
    }

    return new AABB(min,max);

}

int AABB::Collide(Enveloppe * ab)
{
    if(ab->type==1)         // AABB
    {
        printf(" lolol \n");
        AABB * b= (AABB *)(ab);
        printf("LOlilol \n");

        Vectorf * bMin= new Vectorf(*b->min);
        *bMin=*bMin+*b->translation;
        Vectorf * bMax= new Vectorf(*b->max);
        *bMax=*bMax+*b->translation;

        Vectorf * aMax = new Vectorf(*max);
        *aMax= *aMax+*translation;

        Vectorf * aMin = new Vectorf(*min);
        *aMin= *aMin+*translation;

        printf("LOlilol \n");

        if(bMin->x()<aMax->x()&& aMin->x()<bMax->x())
        {
            if(bMin->y()>aMax->y())
            {
                if(bMin->z()>aMax->z())
                {
                    return 1;
                }
            }
        }
        return 0;

    }
    else if(ab->type==2)    // Sphere
    {
        BoundingSphere * b= (BoundingSphere *)(ab);

        float * center=b->translation->Array();
        float * aabbMin=min->Array();
        float * aabbMax=max->Array();

        float s, d = 0;
        //find the square of the distance
        //from the sphere to the box
        for( long i=0 ; i<3 ; i++ )
        {
            if( center[i] < aabbMin[i] )
            {
                s = center[i] -aabbMin[i];
                d += s*s;
            }
            else if( center[i] > aabbMax[i] )
            {
                s = center[i] - aabbMax[i];
                d += s*s;
            }
        }

        return d <= b->rayon*b->rayon;
    }
    else if(ab->type==3)    // Mesh
    {
        return 0;
    }
}

int AABB::SegmentAABBCollisionDetection(Vectorf *u, Vectorf *vertex)
{
    //Vectorf::IntersectionPlan( u, lineVertex, normalPlan, planeVertex);
}
